﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Core.OAuths;
using Web.Core.Security;
using Web.Core.EventArgs;
using Web.Core.Extensions;
using Ayatta.Contract.Config;
using Ayatta.Contract.Domain;

namespace Web.Passport.Controllers
{
    public class ExternalController : BaseController
    {
        public ExternalController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        public void Index()
        {

        }

        /// <summary>
        /// 使用第三方账号登录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult SignIn(string param)
        {
            var client = GetOAuthClient(param);

            if (client != null)
            {
                var url = client.GetLoginUri();
                return Redirect(url);
            }
            return Redirect("/");
        }

        /// <summary>
        /// 验证第三方账号登录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Auth(string param)
        {
            var client = GetOAuthClient(param);
            if (client != null)
            {
                var result = client.Callback(Request.QueryString);
                if (result != null && result.Status)
                {
                    var data = result.Data;
                    var oAuthUser = Passport.Value.OAuthUserGet(data.OpenId, data.CreatedBy);
                    if (oAuthUser != null)
                    {
                        var user = Passport.Value.UserGetByGuid(oAuthUser.Guid);
                        if(user!=null)
                        {
                            var identity = new Identity(user.Id, user.Guid, user.Nickname, user.Role, user.Level, user.Limit, user.Permit, user.Avatar, user.Authenticated);
                            SetAuthCookie(user.Name, false, identity);
                        }
                    }
                    else
                    {
                        
                    }
                   
                }
            }
            return Redirect("/");
        }

        private IOAuthClient GetOAuthClient(string name)
        {
            var key = CacheKey.Passport.OAuths;
            var oAuths = MemcachedClient.Put(key, () => Passport.Value.OAuthList());
            var oAuth = oAuths.FirstOrDefault(o => o.Name.ToLower() == name.ToLower());
            var client = OAuthClientFactory.Create(oAuth);
            client.Authorized += Authorized;
            return client;
        }

        private void Authorized(object sender, EventArgs<OAuthUser> e)
        {
            Passport.Value.OAuthUserSignIn(e.Data);
        }
    }
}
